/*
 * Copyright (C) Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.light.server.persistence.dao;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.light.server.utils.LightPreconditions.checkTxnIsRunning;

import com.google.inject.Inject;
import com.google.light.server.dto.collection.CollectionVersionDto;
import com.google.light.server.dto.pojo.typewrapper.longwrapper.CollectionId;
import com.google.light.server.dto.pojo.typewrapper.longwrapper.Version;
import com.google.light.server.persistence.entity.collection.CollectionEntity;
import com.google.light.server.persistence.entity.collection.CollectionVersionEntity;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import java.util.logging.Logger;

/**
 * DAO for {@link CollectionVersionEntity}.
 * 
 * @author Arjun Satyapal
 */
public class CollectionVersionDao extends AbstractBasicDao<CollectionVersionDto, CollectionVersionEntity> {
  private static final Logger logger = Logger.getLogger(CollectionVersionDao.class.getName());

  static {
    ObjectifyService.register(CollectionVersionEntity.class);
  }

  @Inject
  public CollectionVersionDao() {
    super(CollectionVersionEntity.class);
  }

  /**
   * Put Collection on datastore. Id for {@link CollectionVersionEntity} is generated by DataStore.
   * 
   * {@inheritDoc}
   */
  @Override
  public CollectionVersionEntity put(Objectify ofy, CollectionVersionEntity entity) {
    checkTxnIsRunning(ofy);
    checkNotNull(entity.getCreationTime(), "creationTime for CollectionVersionEntity is mandatory");

    CollectionVersionEntity returnEntity = super.put(ofy, entity);
    String returnMsg = "Created/Updated CollectionVersionEntity[" + returnEntity.getVersion() 
        + "], for Collection[" + returnEntity.getKey().getId() + "].";

    return logAndReturn(logger, returnEntity, returnMsg);
  }

  public CollectionVersionEntity get(Objectify ofy, CollectionId collectionId, Version version) {
    return get(ofy, CollectionEntity.generateKey(collectionId), version);
  }
  
  public CollectionVersionEntity get(Objectify ofy, Key<CollectionEntity> collectionKey, 
      Version version) {
    return super.get(ofy, CollectionVersionEntity.generateKey(collectionKey, version));
  }
}
